﻿/*******************************************************************************
 * @file flash.c
 * @brief flash操作
 *******************************************************************************
*/

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "flash.h"

int Flash_Erase(uint32_t addr, uint32_t size)
{
    /* size 不能为0，没意义 */
    if(size == 0) return -1;

    /* 如果 size==0xFFFFFFFF 则擦除整个flash */
    if(size == UINT32_MAX)
    {
        if(FLASH_EraseAllPages() != FLASH_COMPLETE)
            return -1;

        return 0;
    }

    /* 判断地址和大小是否合法 */
    if(addr < FLASH_BASE || (addr + size - 1) > FLASH_LIMIT)
        return -1;

    // 计算起始页和结束页
    uint32_t start_page = addr & ~(FLASH_PAGE_SIZE - 1);
    uint32_t end_page   = (addr + size - 1) & ~(FLASH_PAGE_SIZE - 1);

    // 遍历并擦除所有涉及的页
    for(uint32_t page = start_page; page <= end_page; page += FLASH_PAGE_SIZE)
    {
        if(FLASH_ErasePage(page) != FLASH_COMPLETE)
        {
            return -1;
        }
    }

    return 0;
}

int Flash_Write(uint32_t addr, const uint16_t *data, uint32_t size)
{
    /* size 不能为0，没意义 */
    if(size == 0) return -1;

    /* 判断地址和大小是否合法 */
    if(addr < FLASH_BASE || (addr + size - 1) > FLASH_LIMIT)
        return -1;

    /* 终止地址 */
    if(size & 0x01) size++;
    uint16_t *end = (uint16_t *)(data + size / 2);

    /* 写flash */
    for(uint16_t *p = (uint16_t *)data; p < end; p++, addr+=2)
    {
        if(FLASH_COMPLETE != FLASH_ProgramHalfWord(addr, *p)) return -1;
    }

    return 0;
}
